package com.tbit.uqbike.webmanager.util.csv.util;

/**
 * @AUTHOR: wei.xing
 * @DATE: 2022-11-19 14:23
 **/

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.io.IOException;
import java.text.SimpleDateFormat;

public class JacksonUtil {
    static ObjectMapper objectMapper = new ObjectMapper();

    static {
        // 忽略json串中多余的字段
        objectMapper.configure(MapperFeature.USE_GETTERS_AS_SETTERS, false);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        //POJO无public的属性或方法时，不报错
        objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        //null值字段不显示
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.activateDefaultTyping(objectMapper.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_ARRAY);

    }

    public static <T> T parseObject(String json, Class<T> clazz) {
        try {
            return objectMapper.readerFor(clazz).readValue(json);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String toStr(Object object) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


}
